<template>
  <div class="app-container">
    <div class="search">
      <!-- 搜索表单 -->
      <el-form :model="searchForm" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="8"
            ><div class="grid-content ep-bg-purple" />
            <el-form-item label="banner名称" prop="account">
              <el-input
                v-model="searchForm.model.name"
                placeholder="请输入查询的banner名称"
                style="width: 200px"
              ></el-input> </el-form-item
          ></el-col>

          <!-- <el-col :span="8"
            ><div class="grid-content ep-bg-purple" />
            <el-form-item label="创建时间" prop="createAt">
              <el-date-picker
                v-model="searchForm.createAt"
                type="daterange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间" /></el-form-item
          ></el-col> -->
        </el-row>
      </el-form>
      <!--重置 搜搜按钮 -->
      <div class="btns">
        <el-button icon="Refresh" @click="handleResetClick">重置</el-button>
        <el-button type="primary" icon="Search" @click="handleQueryClick"
          >查询</el-button
        >
        <el-button type="primary" icon="Upload" @click="handelleAddBtnClick"
          >新建</el-button
        >
      </div>
    </div>

    <!-- 表单 -->
    <div class="content">
      <div class="content">
        <div class="table">
          <el-table
            :data="dataList"
            border
            style="width: 100%; min-height: 400px"
          >
            <el-table-column
              align="center"
              type="index"
              label="序号"
              width="60px"
            />
            <el-table-column
              align="center"
              prop="imgurl"
              label="图片"
              width="150"
            >
              <template #default="scope">
                <!-- <img :src="scope.row.imageUrl" alt="" /> -->
                <el-image
                  style="width: 100px; height: 50px"
                  :z-index="999"
                  preview-teleported
                  :src="scope.row.address"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-src-list="[scope.row.address]"
                  :initial-index="4"
                  fit="cover"
                  ><template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div> </template
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="name" label="名称" />

            <el-table-column
              align="center"
              prop="sort"
              label="排序"
              width="120"
            />
            <el-table-column
              align="center"
              prop="delFlag"
              label="是否展示"
              width="100"
            >
              <!-- 作用域插槽 -->
              <template #default="scope">
                <!-- <el-button
                  size="small"
                  plain
                  :type="scope.row.delFlag === 0 ? 'primary' : 'danger'"
                >
                  {{ scope.row.delFlag === 0 ? "未删除" : "已删除" }}
                </el-button> -->
                <el-switch
                  v-model="scope.row.isShow"
                  :active-value="1"
                  :inactive-value="0"
                  @change="changeShow(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="createTime"
              label="创建时间"
              width="200"
            >
              <template #default="scope">
                {{ formatDateTime(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="updateTime"
              label="更新时间"
              width="200"
            >
              <template #default="scope">
                {{
                  scope.row.updateTime
                    ? formatDateTime(scope.row.updateTime)
                    : ""
                }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="200">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  text
                  icon="Edit"
                  @click="handleEditBtnClick(scope.row)"
                  >编辑</el-button
                >
                <!--  -->

                <el-popconfirm
                  placement="bottom"
                  title="确认删除吗?"
                  width="200"
                  trigger="click"
                  @confirm="handleDeleteBtnClick(scope.row.id)"
                >
                  <template #reference>
                    <el-button size="small" type="danger" text icon="Delete"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <el-pagination
            v-model:current-page="searchForm.current"
            v-model:page-size="searchForm.size"
            :page-sizes="[5, 10, 20]"
            small
            layout="total,sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- dialog对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit === 0 ? '新建' : '编辑'"
      width="50%"
      @close="handleClose"
    >
      <div>
        <el-form
          ref="addFormRef"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="图片" prop="fileList">
            <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleImgChange"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="是否显示" prop="isShow"
            ><el-switch
              v-model="form.isShow"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>

          <el-form-item label="排序" prop="sort">
            <el-input v-model.number="form.sort"> </el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpliadClick">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- <FileUpload /> -->
  </div>
</template>

<script setup>
import { Picture } from "@element-plus/icons-vue";
import { reactive, ref, onMounted } from "vue";
import {
  getBannerListRequest,
  uploadFileRequest,
  deleteBannerRequest,
  editBannerRequest,
} from "@/api/banner";
import { getDeteilImgByIdRequest } from "@/api/buildlibrary";
import { formatDateTime } from "@/utils/index.js";
import { ElMessage } from "element-plus";

import FileUpload from "@/components/fragmentUploaddemo/FileUpload";

const dataList = ref([]); //列表数据

const total = ref(0); //total

const searchForm = reactive({
  size: 5,
  current: 1,
  model: {
    name: "",
  },
});

//新建/编辑 表单
const form = reactive({
  name: "",
  sort: 0,
  fileList: [],
  isShow: 0,
});

const dialogVisible = ref(false);

const rules = reactive({
  name: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { min: 1, max: 20, message: "名称长度必须为1-20", trigger: "blur" },
  ],
  sort: [
    { required: true, message: "请输入排序", trigger: "blur" },
    { type: "number", message: "必须填入数字" },
  ],
  fileList: [{ required: true, message: "请上传图片", trigger: "blur" }],
});

onMounted(() => {
  getList();
});

const getImageUrl = async (id) => {
  // const res = await getDeteilImgByIdRequest(id);
  // let blob = new Blob([res]);
  // let url = window.URL.createObjectURL(blob);
  // console.log(url);
  // return url;
};

// 获取数据
async function getList() {
  const res = await getBannerListRequest(searchForm);
  // 调用接口获取数据
  dataList.value = res.data.list[0];
  // 获取总页数
  total.value = res.data.page.total;

  // 遍历数据，获取图片地址
  dataList.value.forEach(async (item) => {
    item.imageUrl = await getImageUrl(item.address);
  });
}
//重置
function handleResetClick() {
  console.log("reset");
  searchForm.model.name = "";
  searchForm.current = 1;
  searchForm.size = 5;
  getList();
}
//查询操作
function handleQueryClick() {
  console.log("handleQueryClick", searchForm);
  searchForm.current = 1;
  getList();
}

//改变size
const handleSizeChange = (val) => {
  searchForm.size = val;
  getList();
};
//改变页码
const handleCurrentChange = (val) => {
  //设置当前页码
  searchForm.current = val;
  //获取列表数据
  getList();
};

// const fileList = ref([]);

const imageUrl = ref("");
// 上传图片改变事件
const handleImgChange = (uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
  form.fileList = uploadFile.raw;
  addFormRef.value.validateField("fileList");
};

const addFormRef = ref(null);
//新建/编辑 确认操作
const handleUpliadClick = async () => {
  addFormRef.value.validate(async (valid, err) => {
    if (valid) {
      let res = null;
      // 判断是编辑还是新建
      if (isEdit.value === 0) {
        res = await uploadFileRequest(
          form.fileList,
          form.name,
          form.sort,
          form.isShow
        );
      } else {
        res = await editBannerRequest(
          typeof form.fileList === "string" ? "" : form.fileList,
          form.name,
          form.sort,
          form.isShow,
          form.id
        );
      }
      console.log(res);
      if (res.code === 200) {
        ElMessage.success("操作成功");
        dialogVisible.value = false;
        form.fileList;
        getList();
      }
      console.log(res);
    } else {
      console.log(err);
    }
  });
};

//删除banner操作
const handleDeleteBtnClick = async (id) => {
  console.log(id);
  const res = await deleteBannerRequest([id]);
  if (res.code === 200) {
    ElMessage.success("删除成功！");
    getList();
  }
  console.log(res);
};

//dialog框关闭事件
const handleClose = () => {
  imageUrl.value = null;
  form.fileList = null;
  form.name = "";
  form.sort = "";
};

//是否编辑  0新建  1编辑
let isEdit = ref(0);
//新建
const handelleAddBtnClick = () => {
  dialogVisible.value = true;
  isEdit.value = 0;
};
//编辑
const handleEditBtnClick = async (row) => {
  dialogVisible.value = true;
  isEdit.value = 1;
  //回显操作
  console.log(row);
  form.name = row.name;
  form.sort = row.sort;
  form.isShow = row.isShow;
  form.id = row.id;
  form.fileList = row.imageUrl;

  const res = await getDeteilImgByIdRequest(row.address);
  console.log(res);
  // File.value = "1";
  let blob = new Blob([res]);
  let url = window.URL.createObjectURL(blob);
  console.log(url);
  imageUrl.value = row.address;
};

//列表编辑是否显示
const changeShow = async (row) => {
  console.log(row);
  // const res = await updateBannerRequest(row);
  const res = await editBannerRequest(
    "",
    row.name,
    row.sort,
    row.isShow,
    row.id
  );

  if (res.code === 200) {
    ElMessage.success("修改成功！");
    getList();
  }
};
</script>
<style lang="scss" scoped>
label {
  font-weight: 0 !important;
}
.search {
  background-color: #fff;
  padding: 20px;
}
.search .btns {
  text-align: right;
  padding: 0 50px 10px 0;
}
.pagination {
  display: flex;
  justify-content: right;

  margin-top: 30px;
}
:deep(.el-icon.avatar-uploader-icon) {
  width: 100px;
  height: 100px;
}
.avatar {
  width: 120px;
  height: 120px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
</style>
